package com.googlecode.lazyrecords.berkeleydb;

import com.googlecode.lazyrecords.Keyword;
import com.googlecode.lazyrecords.Record;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.SecondaryKeyCreator;

import java.io.UnsupportedEncodingException;

public class KeywordKeyCreator implements SecondaryKeyCreator {
    private final RecordTuple recordTuple;
    private final Keyword<?> keyword;

    public KeywordKeyCreator(RecordTuple recordTuple, Keyword<?> keyword) {
        this.recordTuple = recordTuple;
        this.keyword = keyword;
    }

    @Override
    public boolean createSecondaryKey(SecondaryDatabase secondary, DatabaseEntry key, DatabaseEntry primaryData, DatabaseEntry result) {
        try {
            Record record = recordTuple.entryToObject(primaryData);
            if (record.keywords().contains(keyword)) {
                Object value = record.get(keyword);
                if (value != null) {
                    String text = RecordTuple.MAPPINGS.toString(value.getClass(), value);
                    result.setData(text.getBytes("UTF-8"));
                    return true;
                }
            }
            return false;
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException(e);
        }
    }
}
